#include <REGX52.H>
#include "DS18B20.H"
#include "LCD1602.H"
#include "DELAY.H"
#include "AT24C02.H"
#include "KEY.H"
#include "TIMER0.H"

float T,TShow;//定义TShow的目的是T<0时,T=-T,LCD1602不会显示
char TLow,THigh;

void main()
{
	unsigned char KeyNum;//在标准的 C89 中，变量必须在作用域的顶部（在任何语句之前）声明。
	
	THigh=AT24C02_ReadByte(0);
	TLow=AT24C02_ReadByte(1);
	if(THigh>125 || TLow<-55 || THigh<=TLow)
	{
		THigh=29;
		TLow=24;//！！！TLow保存不了的话，把AT24C02写入的时间延长一点就行
	}
	DS18B20_ConvertT();
	Delay(1000);//清除前面的默认温度（+85）
	
	LCD_Init();
	LCD_ShowString(1,1,"T:");
	LCD_ShowString(2,1,"TH:");
	LCD_ShowString(2,9,"TL:");
	
	Timer0_Init();
	
	while(1)
	{
		KeyNum=Key();
		/*温度读取及显示*/
		DS18B20_ConvertT();
		T=DS18B20_ReadT();
		if(T<0)
		{
			LCD_ShowChar(1,3,'-');
			TShow=-T;
		}
		else
		{
			LCD_ShowChar(1,3,'+');
			TShow=T;//这句要加上
		}
		LCD_ShowNum(1,4,TShow,3);
		LCD_ShowChar(1,7,'.');//小数点
		LCD_ShowNum(1,8,(unsigned int)(TShow*100)%100,2);//显示小数点后2位
		
		/*阈值判断及显示*/
		if(KeyNum)//节约时间
		{
			if(KeyNum==1)
			{
				THigh++;
				if(THigh>=125)THigh=125;
			}
			if(KeyNum==2)
			{
				THigh--;
				if(THigh<=TLow)THigh++;
			}
			if(KeyNum==3)
			{
				TLow++;
				if(THigh<=TLow)TLow--;
			}
			if(KeyNum==4)
			{
				TLow--;
				if(TLow<-55)TLow=-55;
			}
		}
		LCD_ShowSignedNum(2,4,THigh,3);
		LCD_ShowSignedNum(2,12,TLow,3);
		AT24C02_WriteByte(0,THigh);
		Delay(8);
		AT24C02_WriteByte(1,TLow);
		Delay(8);
		
		if(T>THigh)LCD_ShowString(1,13,"OV:H");
		else if(T<TLow)LCD_ShowString(1,13,"OV:L");
		else LCD_ShowString(1,11,"   ");
	}	
}

//定时器扫描按键--按下的时候也能刷新
void Timer0_Routine() interrupt 1
{
	static unsigned int T0Count;

	TL0 = 0x66;				//设置定时初始值
	TH0 = 0xFC;				//设置定时初始值
	T0Count++;
	if(T0Count>=20)//每隔一秒执行一次任务
	{
		T0Count=0;
		Key_Loop();
	}	
}